<template>
  <el-row type="flex" justify="center" align="middle" class="container">
    <el-col class="custom-box">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="80px"
      >
        <el-form-item label="账号" prop="account" :rules="rules.account">
          <el-input v-model="ruleForm.account" clearable></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="pass">
          <el-input v-model="ruleForm.password" show-password></el-input>
        </el-form-item>
        <el-form-item>
          <el-col :span="12" class="custom-btn">
            <el-button type="primary" @click="onSubmit">登录</el-button>
          </el-col>
          <el-col :span="12" class="custom-btn">
            <el-button @click="onRegist">注册</el-button>
          </el-col>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<script lang="ts">
import { Vue, Component } from "vue-property-decorator";
import router from "@/router";
import { rNames } from "@/config/menuConfig";
import { login, setAccount } from "@/utils/account";
import { UsernameAuthProvider } from "tcb-js-sdk/dist/auth/usernameAuthProvider";

@Component({
  name: "Login"
})
export default class Login extends Vue {
  private min = 5;
  private max = 10;
  ruleForm = {
    account: "",
    password: ""
  };

  rules = {
    account: [
      { required: true, message: "请输入账号", trigger: "blur" },
      {
        min: this.min,
        max: this.max,
        message: `长度在 ${this.min} 到 ${this.max} 个字符`,
        trigger: "blur"
      }
    ],
    // 这个pass，不能和ruleForm中的password相同，否则报错。
    pass: [
      {
        min: this.min,
        max: this.max,
        message: `密码的长度需要在 ${this.min} 到 ${this.max} 个字符之间`,
        trigger: "blur"
      },
      { required: true, validator: this.validatePass, trigger: "blur" }
    ]
  };

  validatePass(rule: any, value: any, callback: any) {
    if (value === "") {
      callback(new Error("请输入密码"));
    } else {
      if (this.ruleForm.password !== "") {
        const temp: any = this.$refs.ruleForm;
        temp.validateField("password");
      }
      callback();
    }
  }

  onSubmit() {
    const { account, password } = this.ruleForm;
    login(account, password).then(flag => {
      if (flag) router.push({ name: rNames.home });
    });
  }

  onRegist() {
    router.push({ name: rNames.regist });
  }
}
</script>

<style>
.container {
  height: 100% !important;
}
.custom-box {
  width: fit-content;
  margin-left: -80px;
}
.custom-btn {
  display: flex;
  align-content: center;
  justify-content: center;
}
</style>
